// -----------------------------------------------------------------------
//  <copyright file="SpecificationBase.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/6 15:50:37</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Domain.Entity;


namespace DaprPlus.Specifications;

public abstract class SpecificationBase<T>(Expression<Func<T, bool>> criteria) : ISpecification<T>
    where T : IEntity
{
    private List<Expression<Func<T, object>>> _includes = new();
    private List<string> _includeStrings = new();
    private List<(Expression<Func<T, object>> OrderByExpression, bool IsDescending)> _orderExpressions = new();
    private List<(string FieldName, bool IsDescending)> _orderStrings = new();

    public Expression<Func<T, bool>> Criteria { get; } = criteria;

    public IReadOnlyList<Expression<Func<T, object>>> Includes => _includes.AsReadOnly();

    public IReadOnlyList<string> IncludeStrings => _includeStrings.AsReadOnly();

    public IReadOnlyList<(Expression<Func<T, object>> OrderByExpression, bool IsDescending)> OrderExpressions => _orderExpressions.AsReadOnly();

    public IReadOnlyList<(string FieldName, bool IsDescending)> OrderStrings => _orderStrings.AsReadOnly();


    public bool IsPagingEnabled { get; private set; }

    public int Take { get; private set; }

    public int Skip { get; private set; }

    public ISpecification<T> And(ISpecification<T> specification)
    {
        return new AndSpecification<T>(this, specification);
    }

    public ISpecification<T> Or(ISpecification<T> specification)
    {
        return new OrSpecification<T>(this, specification);
    }

    public ISpecification<T> Not()
    {
        return new NotSpecification<T>(this);
    }

    public ISpecification<T> AndNot(ISpecification<T> specification)
    {
        return new AndSpecification<T>(this, specification.Not());
    }

    public ISpecification<T> OrNot(ISpecification<T> specification)
    {
        return new OrSpecification<T>(this, specification.Not());
    }

    protected void AddInclude(Expression<Func<T, object>> includeExpression)
    {
        _includes.Add(includeExpression);
    }

    protected void AddInclude(string includeString)
    {
        _includeStrings.Add(includeString);
    }

    protected void AddOrderBy(Expression<Func<T, object>> orderByExpression, bool isDescending = false)
    {
        _orderExpressions.Add((orderByExpression, isDescending));
    }

    protected void AddOrderBy(string fieldName, bool isDescending = false)
    {
        _orderStrings.Add((fieldName, isDescending));
    }

    protected void ApplyPaging(int skip, int take)
    {
        Skip = skip;
        Take = take;
        IsPagingEnabled = true;
    }
}
